<?php 
// 附件上传
class DataAction extends Action{
    function _initialize() 
    {
       if(!isset($_SESSION['user_right'])) {
			$this->redirect('login','Public');
        }
        parent::_initialize();
    }
    //入口上传文件index	
	function index()
	{
		$this->display();
        return;
	}
	// 文件上传
    protected function _upload() 
    {
        import("ORG.Net.UploadFile");
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize  = 329220000 ;
        //设置上传文件类型
        $upload->allowExts  = explode(',','dbf');
        //设置附件上传目录
        $upload->savePath =  '../Public/Uploads/'; 

        //执行上传操作
        if(!$upload->upload()) {
            if($this->isAjax() && isset($_POST['_uploadFileResult'])) {
                $uploadSuccess =  false;
                $ajaxMsg  =  $upload->getErrorMsg();
            }else {
                //捕获上传异常
                $this->error($upload->getErrorMsg());            	
            }
        }else{
			$uploadSuccess	=	true;
		}
        // 判断是否有Ajax方式上传附件
        // 并且设置了结果显示Html元素
        if($this->isAjax() && isset($_POST['_uploadFileResult']) ) {
            // Ajax方式上传参数信息
            $info = Array();
            $info['success']  =  $uploadSuccess;
            $info['message']   = $ajaxMsg;
			$info['info']=$upload->getUploadFileInfo();            
            //设置Ajax上传返回元素Id
            $info['uploadResult'] =  $_POST['_uploadFileResult']; 
            if(isset($_POST['_uploadFormId'])) {
                //设置Ajax上传表单Id
                $info['uploadFormId'] =  $_POST['_uploadFormId']; 
            }
            if(isset($_POST['_uploadResponse'])) {
                //设置Ajax上传响应方法名称
                $info['uploadResponse'] =  $_POST['_uploadResponse']; 
            }

            $this->ajaxUploadResult($info);
        }
        return ;
    }

    protected function ajaxUploadResult($info) 
    {
        // Ajax方式附件上传提示信息设置
        // 默认使用mootools opacity效果
        $show   = '<script language="JavaScript" src="'.WEB_PUBLIC_URL.'/Js/mootools.js"></script><script language="JavaScript" type="text/javascript">'."\n";    
        $show  .= ' var parDoc = window.parent.document;';    
        $show  .= ' var result = parDoc.getElementById("'.$info['uploadResult'].'");';   
        if(isset($info['uploadFormId'])) {
   	        $show  .= ' parDoc.getElementById("'.$info['uploadFormId'].'").reset();';
        }
        $show  .= ' result.style.display = "block";';   
        $show .= " var myFx = new Fx.Style(result, 'opacity',{duration:600}).custom(0.1,1);";
        if($info['success']) {
            // 提示上传成功
            $show .=  'result.innerHTML = "<div style=\"color:#3333FF\">文件上传成功！</div>";';
            $url="http://".$_SERVER ['HTTP_HOST'].$_SERVER['PHP_SELF'];
			$show .= 'window.parent.location="'.str_replace("index.php","index.php/Data/selectTable",$url).'";'; 
			$_SESSION["dbffile"]=$info['info'][0]['savename'];        
            // 如果定义了成功响应方法，执行客户端方法
            // 参数为上传的附件id，多个以逗号分割
            if(isset($info['uploadResponse'])) {
                $show  .= 'window.parent.'.$info['uploadResponse'].'();';
            }
        }else {
            // 上传失败
            // 提示上传失败
            $show .=  'result.innerHTML = "<div style=\"color:#FF0000\">上传失败：'.$info['message'].'</div>";';           	
        }
        $show .= "\n".'</script>';   
        $this->assign('_ajax_upload_',$show);   
        return ;
   	}	
	//文件上传
	public function upload() {
		if(!empty($_FILES)) {
			//如果有文件上传 上传附件
			$this->_upload();
			$this->forward();
		}
		echo str_replace("/Index/","/dbf/",$REQUEST_URI);
		$str= "http://".$_SERVER ['HTTP_HOST'].$_SERVER['PHP_SELF'];
		echo str_replace("/upload/","/dbf/",$str);
	}
	
	//数据表选择
	public function selectTable(){
		$model	=	D("Table");
		if ($_SESSION['user_right']=="2")
		{
			$voList="";
		}
		elseif($_SESSION['user_right']=="3")
		{
			$voList[]=array('TABLE'=>"xtu_studentinfo",'COMMENT'=>"学生信息基本表");
		}
		elseif($_SESSION['user_right']=="4")
		{
			$voList=$model->findAll("`TABLE`!='xtu_studentinfo'");
		}
		elseif($_SESSION['user_right']=="5")
		{
			$voList[]=array('TABLE'=>"xtu_graduate",'COMMENT'=>"毕业信息表");
		}
		elseif($_SESSION['user_right']=="6")
		{
			$voList[]=array('TABLE'=>"xtu_studentinfo",'COMMENT'=>"学生信息基本表");
		}
		elseif($_SESSION['user_right']=="7")
		{
			$voList[]=array('TABLE'=>"xtu_party",'COMMENT'=>"党务信息表");
		}
		elseif($_SESSION['user_right']=="8")
		{
			$voList[]=array('TABLE'=>"xtu_assco",'COMMENT'=>"社会活动信息表");
		}										
		else
		{
			$voList=$model->findAll();
		}
		$this->assign('list',$voList);
		$this->display();
	}	
	
	//字段选择
	public function selectField(){
		$_SESSION['PostTable']=$_POST['Table'];
		$_SESSION['PostMethod']=$_POST['PostMethod'];
		$tabName=str_replace(C('DB_PREFIX'),"",$_POST['Table']);
		import("ORG.Io.Dbf");
		$dbf=new readdbf("../Public/Uploads/".$_SESSION["dbffile"],1);
		$modelComment=D("Comment");
		$vo=$modelComment->findAll("`TABLE`='".$tabName."'");
		foreach($vo as $tmp){
			$field[]=array(
			"name"=>$tmp['COMMENT'],
			"field"=>$tmp['FIELD'],
			"dbfname"=>$tmp['DBFNAME'],
			"dbf"=>$dbf->fieldname,
			);	
		}
		//dump($field);
		//exit();
		$this->assign("tabName",$tabName);		
		$this->assign("field",$field);
		$this->display();
	}
	//数据导入html
	public function import(){
		$_SESSION["PostData"]=$_POST;
		$this->display();	
	}

	// 数据导入操作
	public function query() {
		/*发送响应*/
		header('Content-Type: text/html; charset=UTF-8');
		/*导入关联文件*/
		import("ORG.Io.Dbf");
		$Model = new Model(); // 实例化一个model对象 没有对应任何数据表
		if(isset($_SESSION['PostTable'])) $tableName=$_SESSION['PostTable'];
		$dbf=new readdbf("../Public/Uploads/".$_SESSION["dbffile"],1);
		$arr=$dbf->read();
		$_POST=$_SESSION["PostData"];
		$modelComment=D("Comment");
		$voList=$modelComment->findAll("`TABLE`='".$_POST['tabName']."'");		
		foreach($vo as $tmp){
			$field[]=array(
			"name"=>$tmp['COMMENT'],
			"field"=>$tmp['FIELD'],
			"dbfname"=>$tmp['DBFNAME'],
			"dbf"=>$dbf->fieldname,
			);	
		}		
		//unset($_POST["think_html_token"]);
		switch($_SESSION['PostMethod']){
			case "insert":
			$i=0;
			foreach ($arr as $tmp){
				$str="";
				$str.="INSERT INTO `".$tableName."` (";
				foreach ($voList as $vo){
					$str.="`".$vo['FIELD']."`,";
				}
				$str=substr($str,0,strlen($str)-1);
				$str.=") VALUES (";
				foreach ($voList as $vo1){
					$str.="'".$tmp[$_POST[$vo1['FIELD']]]."',";
				}
				$str=substr($str,0,strlen($str)-1);
				$str.=");";
				$Model->execute($str);
				//echo $str."<br>";
				$i++;
				echo "Line:	".$i."<br>";
			}
			break;
			case "update":
			$i=0;
			foreach ($arr as $tmp){
				$str="";
				$str.="UPDATE `".$tableName."` SET";
				foreach ($voList as $vo){
					//忽略空白数据
					if($tmp[$_POST[$vo['FIELD']]])	$str.="`".$vo['FIELD']."`"."='".$tmp[$_POST[$vo['FIELD']]]."',";
				}
				$str=substr($str,0,strlen($str)-1);
				$str.=" where `xh`='".$tmp[$_POST['xh']]."';";
				$Model->execute($str);
				//echo $str."<br>";
				$i++;
				echo "Line:	".$i."<br>";
			}			
			break;
		}
		//提示！
		echo "<script>alert('数据导入完成!');</script>";
	}	

} 
?>